/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-04-16
 * Time: 16:57
 */
class MyBlockingQueue2{
    private String[] data = null;

    //队首
    private int head = 0;

    //队尾
    private int tail = 0;

    private int size = 0;

    public MyBlockingQueue2(int capacity){
        data = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized(this){
            while(size >= data.length){
                this.wait();
            }
        }

        data[tail] = elem;
        tail++;
        if(tail >= data.length){
            tail = 0;
        }

        size++;
        this.notify();
    }

    public String take() throws InterruptedException {
        synchronized(this){
            while(size == 0){
                this.wait();
            }
            String ret = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;

            this.notify();
            return ret;
        }
    }
}

public class demo7 {
    public static void main(String[] args) {
        MyBlockingQueue2 queue1 = new MyBlockingQueue2(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
            while(true){
                try {
                    queue1.put(n + " ");
                    System.out.println("生产者元素" + n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            while(true){
                try {
                    String n = queue1.take();
                    System.out.println("消费者元素" + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
